from var_strategy.finace_manage import Strategy

lva = "close_var_l_ma_fib_m1"
fva = "close_var_f_ma_fib_m1"
va = "close_var_ma_fib_m1"
turn = 'turnover_ma_fib_m1'
cma = 'close_ma_fib_m1'
# 目前可以了， 买入条件加上：close_var_f_ma20 大斜率上涨要看之前的状态是否ok
# 目前可以了， 卖出条件加上：close_var_f_ma20 大斜率下跌就要考虑卖了， 考虑使用责任链模式
class StrategyA(Strategy):

    scale = 0.33
    column = "close_var_f_ma60"

    def __init__(self):
        self.current_stock = ""
        self.max_v = None
        self.min_v = None
        self.is_up = None
        self.can_buy = False
        self.can_sell = False
        self.v = None

    # 一增长比例作为买入条件，下跌作为卖出条件
    def policy(self, stock, row):
        self.v = row[self.column]
        if self.current_stock != stock:
            self.current_stock = stock
            self.max_v = row[self.column]
            self.min_v = row[self.column]
            self.is_up = None
            return self.continue_action()
        if self.is_up is None:
            self.is_up = row[self.column] > self.min_v
            return self.continue_action()
        if self.is_up:
            if row[self.column] > self.max_v:
                self.max_v = row[self.column]
                if self.can_buy:
                    return self.buy()
            elif row[self.column] < self.max_v * (1 - self.scale):
                self.min_v = row[self.column]
                self.is_up = False
                self.can_sell = True
                return self.sell()
        else:
            if row[self.column] < self.min_v:
                self.min_v = row[self.column]
                if self.can_sell:
                    return self.sell()
            elif row[self.column] > self.min_v * (1 + self.scale):
                self.max_v = row[self.column]
                self.is_up = True
                self.can_buy = True
                return self.buy()
        return self.continue_action()

    def buy(self):
        if self.v < 0.15:
            return 0, ""
        print("min:", round(self.min_v, 2), "max:", round(self.max_v, 2),  round(self.v, 2), self.is_up)
        return self.max_v, "buy"

    def sell(self):
        print("min:", round(self.min_v, 2), "max:", round(self.max_v, 2),  round(self.v, 2), self.is_up)
        return self.min_v, "sell"

    def continue_action(self):
        return 0, ""

# close_var_f_ma60    scale = 0.2  1046 次交易， 平均收益率: 0.094
# close_var_f_ma60    scale = 0.25  926 次交易， 平均收益率: 0.12182505399568033
# close_var_f_ma60    scale = 0.30  829 次交易， 平均收益率: 0.14796139927623642 5951945
# close_var_f_ma60    scale = 0.33  789 次交易， 平均收益率: 0.1575411913814955  6052124.841363527
# close_var_f_ma60    scale = 0.33 v= 0.10 554 次交易， 平均收益率: 0.16490974729241875 4727148.020296716
# close_var_f_ma60    scale = 0.33 v= 0.15 454 次交易， 平均收益率: 0.17288546255506604 4111627.2372151655
# close_var_f_ma60    scale = 0.33 v= 0.18 410 次交易， 平均收益率: 0.16639024390243906 3693259.291724603
# turnover_r60        scale = 0.33 v= 0.15 838 次交易， 平均收益率: 0.10121718377088304 3888731.3771250597
